<script setup>
import {computed, ref} from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import Editor from '@/components/Editor.vue'
import {ElTag, ElAutocomplete, ElMessage, ElMessageBox} from 'element-plus'
import _ from 'lodash'


const param = ref({
  id: null,
  title: '',
  cover: '',
  content: '',
  tags: [],
  visibility: 2,
  type: 3,
})

const route = computed(() => router.currentRoute.value);
const postId = route.value.query.postId
console.log("postId: " + postId)

const getPost = async () =>{
  if(postId!==undefined) {
    const  {data} = await getPostDetailService(postId)
    console.log(data.data)
    param.value.title  = data.data.title
    param.value.cover= data.data.cover
    param.value.content = data.data.content
    param.value.tags = data.data.tags
    param.value.visibility = data.data.visibility
    param.value.type = data.data.type
    param.value.id = data.data.id
  }

}
getPost()

import useFileUpload from '@/utiles/common.js'
import {addPost, getTags, updatePost} from "@/api/publish.js";
import submitting from "lodash/seq.js";
import router from "@/router/index.js";
import {getPostDetailService} from "@/api/post.js";

// 封面上传
const coverUpload = useFileUpload({
  endpoint: 'http://localhost:8081/common/upload',
  extraData: {type: 'post'}, // 告诉后端这是头像
  maxSize: 2 * 1024 * 1024,     // 头像限制2MB
  allowedTypes: ['image/jpeg', 'image/png', 'image/jpg']
})

const handleCoverUpload = async (e) => {
  const file = e.target.files[0]
  try {
    const url = await coverUpload.upload(file)
    console.log(url)
    param.value.cover = url
  } catch {
    console.log("上传错误")
  }
}

const query = ref('')
const suggestions = ref([])

// 防抖搜索
const fetchSuggestions = _.debounce(async (queryString, cb) => {
  if (!queryString) {
    cb([])
    return
  }
  console.log("标签:" + queryString)
  try {
    const res = await getTags({tagName: queryString})
    console.log(res.data.data)
    // 转换数据结构为 el-autocomplete 需要的格式
    suggestions.value = res.data.data.map(tag => ({
      value: tag,
      raw: tag
    }))
    cb(suggestions.value)
  } catch (error) {
    console.error('搜索标签失败:', error)
    cb([])
  }
}, 300)

// 选择建议标签
const handleSelect = (item) => {
  if (!param.value.tags.includes(item.raw)) {
    param.value.tags.push(item.raw)
  }
  query.value = ''
}

// 处理输入确认
const handleInputConfirm = () => {
  const newTag = query.value.trim()
  if (newTag) {
    if (!param.value.tags.includes(newTag)) {
      param.value.tags.push(newTag)
    }
  }
  query.value = ''
}

// 删除标签
const removeTag = (tag) => {
  param.value.tags = param.value.tags.filter(t => t !== tag)
  console.log(param.value.tags)
}


// 提交文章
const submit = async () => {
  try {
    submitting.value = true

    await ElMessageBox.confirm(
      '确定要提交文章吗？内容提交后需审核才能公开。',
      '最后确认',
      {
        confirmButtonText: '确认无误，提交',
        cancelButtonText: '再检查一下',
        type: 'warning',
        customClass: 'custom-confirm'
      }
    )
      param.value.type = 3
      console.log(param.value)
      let res = null;
      if(postId!==undefined){
        res = await updatePost(param.value)
      }else {
        res = await addPost(param.value)
      }
      console.log(res.data.data)
      ElMessage.success('发布成功')
      param.value = {
        title: '',
        cover: '',
        content: '',
        tags: [],
        visibility: 2,
        type: 3,
      }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('发布失败')
      console.error('详细错误:', err)
    }
  } finally {
    submitting.value = false
  }
}
//保存草稿
const saveDraft = async () =>{
  try {
    param.value.type = 0
    let res = null;
    if(postId!==undefined){
      res = await updatePost(param.value)
    }else {
      res = await addPost(param.value)
    }
    console.log(res.data.data)
    ElMessage.success('保存草稿成功')
    param.value = {
      title: '',
      cover: '',
      content: '',
      tags: [],
      visibility: 2,
      type: 3,
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('保存草稿失败')
      console.error('详细错误:', err)
    }
  } finally {
    submitting.value = false
  }
}
const fileInput = ref(null)

// 触发文件选择
const triggerUpload = () => {
  fileInput.value.click()
}

// 清除已上传图片
const clearImage = () => {
  param.value.cover = ''
  // 重置输入框值，确保同一张图片可以再次上传
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}
</script>

<template>
  <div class="main">
    <div class="post-container">
      <!-- 标题 -->

      <el-input
        v-model="param.title"
        placeholder="请输入标题"
        class="title-input"
        maxlength="40"
        show-word-limit
      />

      <div class="cover">
        <div class="cover-uploader">
          <!-- 上传提示框 -->
          <div
            class="upload-box"
            @click="triggerUpload"
            :class="{ 'has-image': param.cover }"
          >
            <!-- 无图片状态 -->
            <div v-if="!param.cover" class="upload-placeholder">
              <i class="el-icon-picture-outline upload-icon"></i>
              <p class="upload-text">点击上传封面图片</p>
              <p class="upload-hint">支持JPG、PNG格式，建议尺寸1200×600</p>
            </div>

            <!-- 有图片状态 -->
            <div v-else class="image-preview">
              <el-image
                :src="param.cover"
                class="preview-img"
                fit="cover"
              ></el-image>
              <div class="image-actions">
                <button
                  type="button"
                  class="action-btn replace-btn"
                  @click.stop="triggerUpload"
                >
                  <i class="el-icon-refresh"></i> 替换
                </button>
                <button
                  type="button"
                  class="action-btn delete-btn"
                  @click.stop="clearImage"
                >
                  <i class="el-icon-delete"></i> 移除
                </button>
              </div>
            </div>

            <!-- 实际文件输入框（隐藏） -->
            <input
              type="file"
              ref="fileInput"
              @change="handleCoverUpload"
              accept="image/*"
              class="file-input"
            >
          </div>
        </div>
      </div>

      <!-- 富文本编辑器 -->
      <div class="editor-wrapper">
        <div class="page">
          <Editor  v-model="param.content" />
        </div>
      </div>

      <!-- 设置面板 -->
      <div class="settings-panel">
        <div class="tag-container">
          <!-- 已选标签展示 -->
          <div class="selected-tags">
            <el-tag
              v-for="(tag, index) in param.tags"
              :key="index"
              closable
              @close="removeTag(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>

          <!-- 标签输入框 -->
          <el-autocomplete
            v-model="query"
            :fetch-suggestions="fetchSuggestions"
            placeholder="输入标签"
            clearable
            @select="handleSelect"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          >
            <template #default="{ item }">
              <div>{{ item.value }}</div>
            </template>
          </el-autocomplete>
        </div>

        <!-- 私密性设置 -->
        <div class="setting-item">
          <h4>可见范围</h4>
          <el-radio-group v-model="param.visibility">
            <el-radio :label="0">仅自己可见</el-radio>
            <el-radio :label="1">粉丝可见</el-radio>
            <el-radio :label="2">公开</el-radio>
          </el-radio-group>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" @click="submit">立即发布</el-button>
          <el-button @click="saveDraft">保存草稿</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.post-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08); /* 新增阴影 */
  .title-input {
    margin-bottom: 20px;

    :deep(.el-input__inner) {
      font-size: 18px;
      height: 50px;
      padding: 0 20px;
    }
  }

  .cover .img {
    height: 100px;
  }

  .settings-panel {
    margin-top: 20px;
    padding: 20px;
    border-radius: 4px;

    .setting-item {
      margin-bottom: 24px;

      h4 {
        color: #606266;
        margin: 0 0 12px 0;
        font-size: 14px;
      }
    }

    .action-buttons {
      text-align: right;
      padding-top: 20px;
      border-top: 1px solid #eee;

      .el-button {
        margin-left: 12px;
        min-width: 100px;
      }
    }
  }
}
.cover-uploader {
  margin-bottom: 20px;
}

.upload-box {
  width: 100%;
  min-height: 200px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

// 无图片状态样式
.upload-box:not(.has-image) {
  border: 2px dashed #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;

  &:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
}

.upload-placeholder {
  text-align: center;
  padding: 30px 20px;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
  transition: color 0.3s ease;

  .upload-box:hover & {
    color: #409eff;
  }
}

.upload-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  margin: 0;
}

// 有图片状态样式
.has-image {
  position: relative;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.image-preview {
  width: 100%;
  height: 100%;
  position: relative;
}

.preview-img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  padding: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  transform: translateY(100%);
  transition: transform 0.3s ease;

  .image-preview:hover & {
    transform: translateY(0);
  }
}

.action-btn {
  display: inline-flex;
  align-items: center;
  padding: 5px 12px;
  border-radius: 4px;
  border: none;
  color: #fff;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;

  i {
    margin-right: 4px;
  }
}

.replace-btn {
  background-color: #409eff;

  &:hover {
    background-color: #66b1ff;
  }
}

.delete-btn {
  background-color: #f56c6c;

  &:hover {
    background-color: #f78989;
  }
}

// 隐藏原生文件输入框
.file-input {
  display: none;
}
</style>
